﻿using Orleans;
using System;
using System.Threading.Tasks;
using Volo.Abp.Domain.Entities;

namespace Puppy.Actor
{
    public abstract class ActorBase<TEntity> : Grain<TEntity>, IActor<TEntity>
        where TEntity : IEntity
    {
        /// <summary>
        /// 当前Grain的实际类型
        /// </summary>
        protected Type ActorType { get; }

        public ActorBase()
        {
            ActorType = GetType();
        }

        public Task<TEntity> ReadEntityAsync()
        {
            return Task.FromResult(State);
        }

        public async Task WriteEntityAsync(TEntity entity)
        {
            State = entity;

            await WriteStateAsync();
        }

        public async Task ClearEntityAsync()
        {
            await ClearStateAsync();

            // 取消激活
            DeactivateOnIdle();
        }

        public override string ToString()
        {
            return $"[Actor: {ActorType.Name}] Key: {State.GetKeys()}";
        }
    }
}
